from django import forms
from django_redis import get_redis_connection

from utils.encrypt import md5
from utils.tencent.sms import get_sms
from web import models
from django.core.validators import RegexValidator
from django.core.exceptions import ValidationError


class RegisterModelForm(forms.ModelForm):
    password = forms.CharField(label="密码", widget=forms.PasswordInput())

    # 自定义字段
    confirm_password = forms.CharField(label="重复密码", widget=forms.PasswordInput())

    mobile_phone = forms.CharField(label="手机号", validators=[RegexValidator(r'^(1[3|4|5|6|7|8|9])\d{9}$', '手机号格式错误'), ])

    code = forms.CharField(label="验证码", widget=forms.TextInput())

    class Meta:
        model = models.UserInfo
        fields = ["username", "email", "password", "confirm_password", "mobile_phone", "code"]

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for name, field in self.fields.items():
            field.widget.attrs["class"] = "form-control"
            field.widget.attrs["placeholder"] = "请输入%s" % (field.label, )

    def clean_username(self):
        username = self.cleaned_data["username"]
        exists = models.UserInfo.objects.filter(username=username).exists()
        if exists:
            raise ValidationError("用户名已经存在")
        return username

    def clean_email(self):
        email = self.cleaned_data["email"]
        exists = models.UserInfo.objects.filter(email=email).exists()
        if exists:
            raise ValidationError("邮箱已经存在")
        return email

    def clean_password(self):
        pwd = self.cleaned_data["password"]
        return md5(pwd)

    def clean_confirm_password(self):
        password = self.cleaned_data["password"]
        confirm_password = md5(self.cleaned_data["confirm_password"])
        if password != confirm_password:
            raise ValidationError("两次密码不一致")
        return confirm_password

    def clean_mobile_phone(self):
        mobile_phone = self.cleaned_data["mobile_phone"]
        exists = models.UserInfo.objects.filter(mobile_phone=mobile_phone).exists()
        if exists:
            raise ValidationError("手机号已经注册")
        return mobile_phone

    def clean_code(self):
        code = self.cleaned_data["code"]
        mobile_phone = self.cleaned_data["mobile_phone"]

        conn = get_redis_connection()
        redis_code = conn.get(mobile_phone)
        if not redis_code:
            raise ValidationError("验证码失效或未发送，请重新发送")

        redis_code_str = redis_code.decode("utf-8")
        if code.strip() != redis_code_str:
            raise ValidationError("验证码错误，请重新输入")

        return code

class SendSmsForm(forms.Form):
    mobile_phone = forms.CharField(label="手机号", validators=[RegexValidator(r'^(1[3|4|5|6|7|8|9])\d{9}$', '手机号格式错误'), ])

    def __init__(self, request, *args, **kwargs):
        """ request可以使用传过来的数据 """
        super().__init__(*args, **kwargs)
        self.request = request

    def clean_mobile_phone(self):
        mobile_phone = self.cleaned_data['mobile_phone']

        exists = models.UserInfo.objects.filter(mobile_phone=mobile_phone).exists()
        if exists:
            raise ValidationError("手机号已经存在")

        # 发短信 & 写入redis
        code = get_sms()
        print("code======", code)
        # 写入redis
        conn = get_redis_connection()
        conn.set(mobile_phone, code, ex=60)

        return mobile_phone
